module KeyScanDebounce(
    input clk,
    input rst_n,
    input [8:0] key_in_n,
    output reg key_ready,
    output reg [3:0] key_num
);

    reg [19:0] debounce_cnt [8:0];
    reg [8:0] key_state;
    reg [8:0] key_state_last;
    integer i;
    reg key_locked;

    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            key_ready <= 0;
            key_num <= 0;
            key_locked <= 0;
            for (i=0; i<9; i=i+1) begin
                debounce_cnt[i] <= 0;
                key_state[i] <= 1;
                key_state_last[i] <= 1;
            end
        end else begin
            key_ready <= 0;
            for (i=0; i<9; i=i+1) begin
                if (key_in_n[i] == 0) begin
                    if (debounce_cnt[i] < 20'hFFFFF)
                        debounce_cnt[i] <= debounce_cnt[i] + 1;
                    if (debounce_cnt[i] > 100000)
                        key_state[i] <= 0;
                end else begin
                    debounce_cnt[i] <= 0;
                    key_state[i] <= 1;
                end
            end

            if (!key_locked) begin
                for (i=0; i<9; i=i+1) begin
                    if (key_state[i] == 0 && key_state_last[i] == 1) begin
                        key_ready <= 1;
                        key_num <= i + 1;
                        key_locked <= 1;
                        break;
                    end
                end
            end else begin
                if (key_state[key_num - 1] == 1)
                    key_locked <= 0;
            end

            for (i=0; i<9; i=i+1)
                key_state_last[i] <= key_state[i];
        end
    end
endmodule
